﻿<%@ WebHandler Language="C#" Class="ReBiaoContainerUploadHandler" %>

using System;
using System.Web;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Linq;
using BusinessRule.Business;
using System.Data;
using Newtonsoft.Json;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using System.Collections;
using BusinessRule.DTO;
using System.Web.SessionState;

public class ReBiaoContainerUploadHandler : IHttpHandler, IRequiresSessionState
{
    private RbContainerBusiness rbContainerBusiness = new RbContainerBusiness();
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request.Form["action"].ToString();
            switch (action)
            {
                case "GetPageList":
                    GetPageList(context);
                    break;
                case "ExcelUpload":
                    ExcelFileToTable(context);
                    break;
                case "Save":
                    SaveData(context);
                    break;
                case "Deletes":
                    DeleteRbContainerInfo(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception e)
        {
            context.Response.Write(JsonConvert.SerializeObject(new ReSultData() { Msg = "出错了：" + e.Message, result = false }));
        }
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    /// <summary>
    /// 查询获取列表
    /// </summary>
    /// <param name="context"></param>
    public void GetPageList(HttpContext context)
    {
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("pageNumber", context.Request.Form["pageNumber"].ToString());//页码
        para.Add("pageSize", context.Request.Form["pageSize"].ToString());//每页页数
        if (context.Request.Form["SpecNos"] != null && !string.IsNullOrWhiteSpace(context.Request.Form["SpecNos"].ToString()))
        {
            para.Add("SpecNos", System.Web.HttpUtility.UrlDecode(context.Request["SpecNos"].ToString()));//add:Wangjh 20211125
        
        }
        
        string productNo = System.Web.HttpUtility.UrlDecode(context.Request["productNo"].ToString());
        if (!string.IsNullOrWhiteSpace(productNo))
        {
            para.Add("productNo", productNo.Trim());//件号
        }
        if (context.Request.Form["stepNo"] != null && !string.IsNullOrWhiteSpace(context.Request.Form["stepNo"].ToString()))
        {
            string stepNo = context.Request.Form["stepNo"].ToString();
            if (!string.IsNullOrWhiteSpace(stepNo))
            {
                para.Add("stepNo", stepNo.Trim());//工序号
            }
        }
        if (context.Request.Form["productNos"] != null && !string.IsNullOrWhiteSpace(context.Request.Form["productNos"].ToString()))
        {
            para.Add("ProductNos", System.Web.HttpUtility.UrlDecode(context.Request.Form["productNos"].ToString()));//件号s
        }

        var list = rbContainerBusiness.GetRbContainerInfo(para);
        ReSultData res = new ReSultData() { TotalCount = list.RowCount, Data = list.DBTable };
        context.Response.Write(JsonConvert.SerializeObject(res));
    }

    /// <summary>
    /// 保存勾选的数据
    /// </summary>
    /// <param name="context"></param>
    public void SaveData(HttpContext context)
    {
        CurrentUserInfo m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["tableData"].ToString());
        List<Dictionary<string, string>> dicList = new List<Dictionary<string, string>>();
        //DataTable temdt = rbContainerBusiness.GetContainerTemList();
        bool isUser = true;
        foreach (DataRow item in dt.Rows)
        {
            if (!dt.Columns.Contains("Msg"))//如果不包含提示列，则添加
            {
                dt.Columns.Add("Msg");
            }
            item["Msg"] = "";
            DataTable temdt = rbContainerBusiness.GetContainerTemList(item["FILENAME"].ToString());
            if (string.IsNullOrWhiteSpace(item["PRODUCTNAME"].ToString()) || string.IsNullOrWhiteSpace(item["SPECNO"].ToString()))
            {
                isUser = false;
                item["Msg"] = "未填写工序号或者零件号";
                continue;
            }
            if (temdt.Rows .Count ==0)
            {
                isUser = false;
                item["Msg"] = "未找到该文件模板";
                item["FILEPATH"] = "";
                continue;
            }
            item["FILEPATH"] = "Temp/ReBiaoContainerTemplate/" + item["FILENAME"].ToString().Trim();
            if (isUser)
            {
                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic.Add("RBContainerTemplateId", item["RBCONTAINERTEMPLATEID"].ToString());
                dic.Add("ProductName", item["PRODUCTNAME"].ToString().Trim());
                dic.Add("SpecNo", GetSpecNo(item["SPECNO"].ToString().Trim()));
                dic.Add("FileName", item["FILENAME"].ToString().Trim());
                dic.Add("FilePath", @"Temp/ReBiaoContainerTemplate/" + item["FILENAME"].ToString().Trim());
                dic.Add("CreateEmployeeId", m_UserInfo.EmployeeID.ToString());
                dicList.Add(dic);
            }
        }
        if (isUser)
        {
            rbContainerBusiness.SaveExcelData(dicList);
            context.Response.Write(JsonConvert.SerializeObject(new ReSultData() { Msg = "导入完成", result = true }));
        }
        else
        {
            context.Response.Write(JsonConvert.SerializeObject(new ReSultData() { Msg = "数据有误，请检查后再保存", result = false, Data = dt, TotalCount = dt.Rows.Count.ToString() }));
        }
    }
    /// <summary>
    /// 删除数据
    /// </summary>
    /// <param name="context"></param>
    public void DeleteRbContainerInfo(HttpContext context)
    {
        try
        {
            DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["deleTableData"].ToString());
            foreach (DataRow item in dt.Rows)
            {
                string rid = item["RBCONTAINERTEMPLATEID"].ToString();
                if (!string.IsNullOrWhiteSpace(rid))
                {
                    rbContainerBusiness.DeleteRbContainerById(rid);
                }
            }
            context.Response.Write(JsonConvert.SerializeObject(new ReSultData() { Msg = "删除完成！", result = true }));
        }
        catch
        {
            context.Response.Write(JsonConvert.SerializeObject(new ReSultData() { Msg = "删除出错！", result = false }));
        }
    }
    /// <summary>
    /// 处理上传的EXCEL文件
    /// </summary>
    /// <param name="context"></param>
    public void ExcelFileToTable(HttpContext context)
    {
        try
        {
            var files = context.Request.Files;
            if (files.Count == 0)
            {
                context.Response.Write(JsonConvert.SerializeObject(new ReSultData() { Msg = "未上传文件！", result = false }));
                return;
            }
            var file = files.Count > 1 ? files[files.Count - 1] : files[0];
            string IsXls = Path.GetExtension(file.FileName);
            string fpath = context.Server.MapPath(@"/InSiteWebApplication/Ashx/ReBiaoConainer/" + file.FileName);
            file.SaveAs(fpath);
            //读取文件流
            FileStream fileStream = new FileStream(fpath, FileMode.Open, FileAccess.Read);
            fileStream.Position = 0;
            IWorkbook Workbook = null;
            IRow row = null;
            try
            {
                switch (IsXls)
                {
                    case ".xlsx":
                        Workbook = new XSSFWorkbook(fileStream);
                        break;
                    case ".xls":
                        Workbook = new HSSFWorkbook(fileStream);
                        break;
                    default:
                        context.Response.Write(JsonConvert.SerializeObject(new ReSultData() { Msg = "文件格式不对！", result = false }));
                        return;
                }
            }
            catch
            {
                fileStream.Close();
                context.Response.Write(JsonConvert.SerializeObject(new ReSultData() { Msg = "出错了！", result = false }));
                return;
            }
            fileStream.Close();
            
            DataTable dt = new DataTable();
            dt.Columns.Add("PRODUCTNAME");
            dt.Columns.Add("SPECNO");
            dt.Columns.Add("FILENAME");
            dt.Columns.Add("FILEPATH");
            dt.Columns.Add("Msg");
            dt.Columns.Add("RBCONTAINERTEMPLATEID");
            ISheet sheet = Workbook.GetSheetAt(0);
            IEnumerator rows = sheet.GetRowEnumerator();
            rows.MoveNext();//跳过表头
            while (rows.MoveNext())
            {
                switch (IsXls)
                {
                    case ".xlsx":
                        row = (XSSFRow)rows.Current;
                        break;
                    case ".xls":
                        row = (HSSFRow)rows.Current;
                        break;
                }
                if (row.Cells.Count == 0)//如果单元格为空，结束
                {
                    break;
                }
                if (string.IsNullOrWhiteSpace(row.GetCell(0).ToString().Trim()) || string.IsNullOrWhiteSpace(row.GetCell(1).ToString().Trim()) || string.IsNullOrWhiteSpace(row.GetCell(2).ToString().Trim()))//只要有数据为空，结束
                {
                    break;
                }
                DataRow dr = dt.NewRow();
                dr["PRODUCTNAME"] = row.GetCell(0).ToString().Trim();
                dr["SPECNO"] = GetSpecNo(row.GetCell(1).ToString().Trim());
                if (string.IsNullOrWhiteSpace(row.GetCell(0).ToString().Trim()) || string.IsNullOrWhiteSpace(row.GetCell(1).ToString().Trim()))
                {
                    dr["Msg"] = "未填写件号或者工序号";
                }
                dr["FILENAME"] = row.GetCell(2).ToString().Trim();
                dr["FILEPATH"] = "";
                DataTable temdt = rbContainerBusiness.GetContainerTemList(row.GetCell(2).ToString().Trim());
                //DataRow temdr = temdt.Select(string.Format("FILENAME = '{0}'", row.GetCell(2).ToString().Trim())).FirstOrDefault();

                if (string.IsNullOrWhiteSpace(Path.GetExtension(row.GetCell(2).ToString().Trim())))//如果文件没有扩展名
                {
                    dr["Msg"] = "该文件名没有扩展名";
                }
                else if (temdt.Rows .Count ==0)
                {
                    dr["Msg"] = "未找到该文件模板";
                }
                else
                {
                    dr["Msg"] = "";
                    dr["FILEPATH"] = "Temp/ReBiaoContainerTemplate/" + row.GetCell(2).ToString().Trim();
                }
                dr["RBCONTAINERTEMPLATEID"] = "";
                dt.Rows.Add(dr);
            }
            if (File.Exists(fpath))//上传完并删除掉
            {
                new FileInfo(fpath).Attributes = FileAttributes.Normal;
                File.Delete(fpath);
            }
            context.Response.Write(JsonConvert.SerializeObject(new ReSultData() { Msg = "导入完成", result = true, Data = dt, TotalCount = dt.Rows.Count.ToString() }));
        }
        catch (Exception e)
        {
            context.Response.Write(JsonConvert.SerializeObject(new ReSultData() { Msg = e.Message, result = false }));
        }
    }
    /// <summary>
    /// 转换工序号
    /// </summary>
    /// <param name="specNo"></param>
    /// <returns></returns>
    private string GetSpecNo(string specNo)
    {
        int len = specNo.Length;
        switch (len)
        {
            case 1:
                return specNo = "000" + specNo;
            case 2:
                return specNo = "00" + specNo;
            case 3:
                return specNo = "0" + specNo;
            default:
                return specNo;
        }

    }

    /// <summary>
    /// 返回页面的json对象
    /// </summary>
    public class ReSultData
    {
        public string TotalCount { get; set; }
        public string Msg { get; set; }
        public bool result { get; set; }
        public DataTable Data { get; set; }
    }



}